package org.summer.generator.writer;

import org.summer.generator.channel.FileWriterChannel;
import org.summer.generator.config.ProjectConfig;
import org.summer.generator.config.WriterConfig;
import org.summer.generator.vo.MethodInfo;
import org.summer.generator.vo.Table;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 文件写入接口实现类抽象父类，实现公共操作
 */
public abstract class AbstractFileWriter implements FileWriter {
    protected static final ConcurrentHashMap<String, List<MethodInfo>> METHOD_CACHE = new ConcurrentHashMap<>();
    protected final Set<String> importSet = new HashSet<>();
    protected static final String MAPPER_INSERT = "insert";
    protected static final String MAPPER_UPDATE = "update";
    protected static final String MAPPER_DELETE = "delete";
    protected static final String MAPPER_SELECT = "select";
    /**
     * 文件写入通道
     */
    protected FileWriterChannel channel;
    /**
     * 项目配置信息
     */
    protected ProjectConfig project;
    /**
     * 文件写入操作配置信息
     */
    protected WriterConfig writer;
    /**
     * 数据库表信息实体
     */
    protected Table table;
    @Override
    public void setChannel(FileWriterChannel channel) {
        this.channel = channel;
    }

    @Override
    public void setProjectConfig(ProjectConfig config) {
        this.project = config;
    }

    @Override
    public void setWriterConfig(WriterConfig config) {
        this.writer = config;
    }

    @Override
    public void setTable(Table table) {
        this.table = table;
    }


    /**
     * 解析方法返回值类型
     */
    private String parseMethodReturnType(Method method) {
        String typeName = method.getGenericReturnType().getTypeName();
        if (typeName.contains("T")) {
            // 泛型类型
            typeName = typeName.replace("T", table.getTableUpperName());
        }
        if (typeName.contains("I")) {
            // 泛型类型
            typeName = typeName.replace("I", table.getIdType());
        }
        if (typeName.contains(".")) {
            // 解析需要导入的类
            addImport(method.getReturnType().getName());
            // 将完整类名简化为简单类名字
            String[] split = typeName.split("\\.");
            typeName = split[split.length - 1];
        }
        return typeName;
    }

    /**
     * 解析方法的参数信息
     */
    private void parseMethodParameter(Method method, MethodInfo methodInfo) {
        List<String> parameter = new ArrayList<String>();
        Parameter[] ps = method.getParameters();
        String paramName = "";
        String paramTypeAndName = "";
        int i = 0;
        for (Parameter p : ps) {
            String temp = p.getParameterizedType().getTypeName();
            if (temp.contains("T") && (temp.contains("<") || temp.length() == 1)) {
//                // 泛型类型
                temp = temp.replace("T", table.getTableUpperName());
            }
            if (temp.contains("I") && (temp.contains("<") || temp.length() == 1)) {
                // 主键类型
                temp = temp.replace("I", table.getIdType());
            }
            if (temp.contains(".")) {
                addImport(p.getType().getName());
                // 处理类全名为简单类名
                String[] split = temp.split("\\.");
                temp = split[split.length - 1];
            }
            parameter.add(temp + " " + p.getName());
            if (i > 0){
                paramName += ", ";
                paramTypeAndName += ", ";
            }
            paramName += p.getName();
            paramTypeAndName += temp + " " + p.getName();
            i ++;
        }
        methodInfo.setParameter(parameter);
        methodInfo.setParamName(paramName);
        methodInfo.setParamTypeAndName(paramTypeAndName);
    }

    /**
     * 添加类导入
     *
     * @param importClass 需要导入的类
     */
    protected void addImport(String importClass) {
        if (!importClass.startsWith("java.lang")) {
            importSet.add("import " + importClass + ";");
        }
    }

    /**
     * 解析方法类方法定义
     */
    protected List<MethodInfo> parseMethodDefinitions(String className) {
        List<MethodInfo> mds = getCachedMethodParseResult(className);
        if (mds != null){
            return mds;
        }
        mds = new ArrayList<>();
        try {
            Class<?> _class = Class.forName(className);
            Method[] methods = _class.getMethods();
            for (Method method : methods) {
                MethodInfo mi = new MethodInfo();
                if (Modifier.isAbstract(method.getModifiers())) {
                    String returnType = parseMethodReturnType(method);
                    mi.setModifier(Modifier.toString(method.getModifiers()));
                    mi.setMethodName(method.getName());
                    mi.setReturnType(returnType);
//                    mi.setParameter(parseMethodParameter(method));
                    parseMethodParameter(method, mi);
                    mds.add(mi);
                }
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("没有找到控制器父接口类[%s]".formatted(writer.getControllerParentInterface()));
        }
        cacheMethodParseResult(className, mds);
        return mds;
    }

    private void cacheMethodParseResult(String key, List<MethodInfo> methodInfos){
        METHOD_CACHE.put(key, methodInfos);
    }

    private List<MethodInfo> getCachedMethodParseResult(String key){
        return METHOD_CACHE.get(key);
    }
}
